#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#define PORT 8080
#define BUFFER_SIZE 1024

int main() {
    int sock = 0;
    struct sockaddr_in serv_addr;
    char buffer[BUFFER_SIZE] = {0};
    char message[BUFFER_SIZE];

    // 从命令行读取输入
    printf("请输入: ");
    fgets(message, BUFFER_SIZE, stdin);
    // 去除换行符
    message[strcspn(message, "\n")] = '\0';

    // 创建客户端 socket
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket creation error");
        exit(EXIT_FAILURE);
    }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);

    // 将 IP 地址从点分十进制转换为网络字节序
    if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
        perror("invalid address/ address not supported");
        exit(EXIT_FAILURE);
    }

    // 连接到服务器
    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("connection failed");
        exit(EXIT_FAILURE);
    }

    // 发送数据到服务器
    if (send(sock, message, strlen(message), 0) < 0) {
        perror("send failed");
        exit(EXIT_FAILURE);
    }
    printf("发送给服务器的数据: %s\n", message);

    // 接收服务器的响应
    while(1)
    {
        int valread = read(sock, buffer, 1024);
        if (valread == 0) {
            printf("服务器已关闭连接\n");
            break;
        }
        printf("收到服务器的响应: %s\n", buffer);
    }


    // 关闭 socket
    close(sock);
    return 0;
}